#include "creategroup.h"
#include "ui_creategroup.h"

Creategroup::Creategroup(QString uName,QWidget *parent) :
    QWidget(parent),uName(uName),
    ui(new Ui::Creategroup)
{
    ui->setupUi(this);
    tcpClient=new QTcpSocket(this);
    QString LocalIP=getLocalIP();
    //连接服务器
    quint16 targetport=8888;
    tcpClient->connectToHost(LocalIP,targetport);
    connect(tcpClient, SIGNAL(readyRead()), this, SLOT(processPendingDatagrams()));
}

Creategroup::~Creategroup()
{
    delete ui;
}

QString Creategroup::getLocalIP()
{
    QString hostName=QHostInfo::localHostName();
    QHostInfo hostInfo=QHostInfo::fromName(hostName);
    QString localIP="";
    QList<QHostAddress> addList=hostInfo.addresses();
    if(!addList.isEmpty())
    {
        for(int i=0;i<addList.count();i++)
        {
            QHostAddress aHost=addList.at(i);
            if(QAbstractSocket::IPv4Protocol==aHost.protocol())
            {
                localIP=aHost.toString();
                break;
            }
        }
    }
    return localIP;
}

void Creategroup::on_submit_pushButton_clicked()//提交创建群的请求
{
    QString groupname=ui->groupname_lineEdit->text();
    QString ugadminname=uName;
    QString createtime=QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    QString nickname=ui->nickname_lineEdit->text();
    QByteArray data;
    QDataStream out(&data, QIODevice::WriteOnly);
    out<< quint8('N')<<groupname<<ugadminname<<createtime<<nickname;//A1表示进行添加好友操作
    tcpClient->write(data);//发送数据


}

void Creategroup::processPendingDatagrams()
{
    QByteArray datagram;
    datagram=tcpClient->readAll();
    QDataStream in(&datagram,QIODevice::ReadOnly);
    QString avail_username;
    quint8 type;
    QString info;
    in>>type;
    //
    if(type=='D')//数据库出错
    {
        in>>info;
        QMessageBox::warning(0,tr("警告"),"数据库出错"+info,QMessageBox::Ok);
    }
    else if(type=='F') //提交信息有误，名字被占用了
    {
         in>>info;
         QMessageBox::warning(0,tr("警告"),"名称已被占用"+info,QMessageBox::Ok);
    }
    else if(type=='S')
    {
        QMessageBox::information(0,tr("提示"),tr("创建成功"),QMessageBox::Ok);
    }
}

